package project.background.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;

import fld.background.entity.FileInfo;
import fld.background.service.FileInfoService;
import fld.background.system.controller.BaseController;
import fld.utils.Common;

/**
 * 文件上传
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/uploadfile/")
public class UploadFileController extends BaseController {

	@Autowired
	private FileInfoService fileInfoService;
	
	@Value("${fileUrl}")
	private String fileUrl;

	/**
	 * 上传
	 * 
	 * @param t
	 * @return
	 * @author yc
	 * @date 2017年7月2日
	 */
	@ResponseBody
	@RequestMapping(value = "fileupload")
	public String fileupload(@RequestParam(value = "file", required = false) MultipartFile file) {
		Date d = new Date();
		String code = fileInfoService.getCode(d);
		String dir = fileUrl + fileInfoService.createUrl(d);
		try {
			CommonsMultipartFile cf = (CommonsMultipartFile) file; // 这个myfile是MultipartFile的
			FileItem fit = cf.getFileItem();
			String fileName = fit.getName();
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			String url = dir + code + suffix;
			File f = new File(url);
			if (!f.exists()) {
				f.getParentFile().mkdirs();
				f.createNewFile();
			}

			BufferedInputStream in = null;
			BufferedOutputStream out = null;
			try {
				in = new BufferedInputStream(file.getInputStream());
				out = new BufferedOutputStream(new FileOutputStream(f));

				int len = -1;
				byte[] b = new byte[1024];
				while ((len = in.read(b)) != -1) {
					out.write(b, 0, len);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			suffix = suffix.toLowerCase();
			if(".jpg".equals(suffix) || ".jpeg".equals(suffix) || ".png".equals(suffix) || ".bmp".equals(suffix) || ".gif".equals(suffix)){
				try {
					fileInfoService.createSmallImg(dir, code, suffix);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			FileInfo fi = new FileInfo();
			fi.setName(fileName);
			fi.setSuffix(suffix);
			fi.setCode(code);
			fi.setSize(String.valueOf(file.getSize()));
			fi.setOurl("");
			fi.setSurl(url);
			fileInfoService.saveObj(fi);
		} catch (IOException e) {
			return getError("文件获取错误");
		}

		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", request.getContextPath()+"/uploadfile/image/"+code);
		return obj.toJSONString();
	}

	/**
	 * 根据code获取图片
	 * @param request
	 * @param response
	 * @param code
	 * @author yc
	 * @throws IOException 
	 * @date 2017年7月9日
	 */
	@RequestMapping(value = "image/{code}")
	public void getImage(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code,String imgtype) throws IOException {
		 //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型   
        response.setContentType("multipart/form-data");   
		FileInfo t = fileInfoService.queryByCode(code);
		if(null != t){
			 //2.设置文件头：最后一个参数是设置下载文件名
	        response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(t.getName(),"UTF-8"));   
	        FileInputStream in = null;
	        OutputStream ots = response.getOutputStream();
	        String fileUrl = t.getSurl();
			try {
				
				if(!"".equals(Common.nullToEmpty(imgtype))){
					fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("."))+ imgtype+fileUrl.substring(fileUrl.lastIndexOf("."));
				}
				File file = new File(fileUrl);
				in = new FileInputStream(file);
				byte[] buf = new byte[1024];
				int len = 0;
		      	while((len=in.read(buf))>0){      
		      		ots.write(buf,0,len);
		      	}
		      	ots.flush();
			} catch(FileNotFoundException e){
				System.out.println("文件找不到："+fileUrl);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (in != null) {
					try {
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (ots != null) {
					try {
						ots.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}
